package com.example.onlinejudge.service;

import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class CommandUtilService {
    public int run(String cmd, String stdoutFile, String stderrFile) throws IOException, InterruptedException {
        // 1. 通过 Runtime 类得到 Runtime 实例, 执行 exec 方法
        Process process=Runtime.getRuntime().exec(cmd);
        //2.获取标准输出并写入指定文件
        InputStream stdoutFrom= process.getInputStream();
        if(stdoutFile!=null){
            getAndWrite(stdoutFile, stdoutFrom);
        }
        //3.获取标准错误并写入指定文件
        InputStream stderrFrom= process.getErrorStream();
        if(stderrFile!=null){
            getAndWrite(stderrFile, stderrFrom);
        }
        // 4. 等待子进程结束, 拿到子进程的状态码, 并返回.
        int exitCode = process.waitFor();
        return exitCode;
    }

    public void getAndWrite(String stdoutFile, InputStream stdoutFrom) throws IOException {
        FileOutputStream stdoutTo = new FileOutputStream(stdoutFile);
        while(true){
            int ch=stdoutFrom.read();
            if(ch==-1){
                break;
            }
            stdoutTo.write(ch);
        }
        stdoutFrom.close();
        stdoutTo.close();
    }
}
